/**
 * @author jh
 * @desc 编辑字段页面组件
 *
 */
import React from "react";
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { WeaSwitch } from 'comsMobx';
import { Button, Row, Modal, Spin, Icon } from 'antd';
import {
    WeaTools,
    WeaDialog,
    WeaCollect,
    WeaRichText,
    WeaFormItem,
    WeaRightMenu,
    WeaMoreButton,
    WeaSearchGroup,
    WeaLocaleProvider,
    WeaAlertPage,
} from 'ecCom';

import { RichTextTitle } from "./RichTextTitle";

import isRegExp from 'lodash/isRegExp';
const getLabel = WeaLocaleProvider.getLabel;


@observer
export default class Main extends React.Component {

    constructor(props) {
        super(props);

        this.getDialogBtns;

        this.state = {
            // isRequired: 'required',
            showCollect: false,
        }
    }
    componentWillUnmount() {
        const { store } = this.props;
        const { clearStore } = store;
        clearStore();
    }

    render() {
        const { store, visiable, setVisiable, maxRows = 20, minRows = 20,controlLayout } = this.props;
        const {
            onCancelEdit,
            form,
            success,
            conditions,
            richTextOnChange,
            phraseDescValue,
            useTextAreaSignInput,
            isRequired,
            loading,
            phraseEditDialogTitle
        } = store;
        const formParams = form.getFormParams();
        const { showCollect } = this.state;

        let conditionGroup = [];
        let extentsConfig = [];
        this.initExtentsConfig(extentsConfig);
        if (loading) {
            const antIcon = <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@6uz6xl`} type="loading" style={{ fontSize: 24 }} spin />;
            conditionGroup.push(<div style={{
                width: "100%",
                height: "100px",
                marginTop: "280px",
                textAlign: "center",
            }}>
                <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@cvw1eg@ec1`} wrapperClassName="wf-phrase-loading" size="large" indicator={antIcon} />
            </div>)
        } else if (success == -1) {
            conditionGroup.push(
                <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@srh0yb@ec2`}
                    icon={<i className="icon-coms-locking" style={{ color: 'rgb(203, 203, 203)' }} />}
                    iconSize={120}
                    paddingTop={'15%'}
                >
                    <div style={{ color: 'rgb(154, 154, 154)', paddingTop: "10px" }}>
                        对不起，您暂时没有权限 ！
                    </div>
                </WeaAlertPage>
            );
        } else if (success == 0) {
            conditionGroup.push(
                <WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@r1dfui@ec3`}
                    icon={<i className="icon-coms-locking" style={{ color: 'rgb(203, 203, 203)' }} />}
                    iconSize={120}
                    paddingTop={'15%'}
                >
                    <div style={{ color: 'rgb(154, 154, 154)', paddingTop: "10px" }}>
                        发生异常，请刷新重新或联系管理员
                    </div>
                </WeaAlertPage>
            )
        } else {
            form.isFormInit && conditions && conditions.map((g, index) => {
                index == 0 ? conditionGroup.push(
                    <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@zar1ot@${index}`}
                        needTigger={true}
                        title={g.title}
                        center
                        showGroup={g.defaultshow}
                    >
                        {
                            g.items && g.items.map((item) => {
                                const domKey = typeof item.domkey === "object" ? item.domkey[0] : item.domkey;
                                if (item.domkey[0] === 'dsporder') {
                                    item.regExp = /^(-{0,1}|(-{0,1}[0-9]{1,}[.]?[0-9]*))$/;
                                }
                                return (
                                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8wbhtl@${domKey}`}>
                                        <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@el88pj@${domKey}`}
                                            label={`${item.label}`}
                                            labelCol={{ span: `${item.labelcol}` }}
                                            wrapperCol={{ span: `${item.fieldcol}` }}
                                            error={form.getError(item)}
                                            tipPosition={'bottom'}
                                        >
                                            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@ig8met@${domKey}`}
                                                fieldConfig={item}
                                                form={form}
                                                formParams={formParams}
                                            />
                                        </WeaFormItem>
                                    </Row>
                                )
                            })
                        }
                    </WeaSearchGroup>
                )
                    :
                    conditionGroup.push(
                        <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@uwi8mr@group1`}
                            needTigger={true}
                            title={<RichTextTitle ecId={`${this && this.props && this.props.ecId || ''}_RichTextTitle@tpqkdc@ec1`} isRequired={phraseDescValue ? "" : isRequired} />}
                            showGroup={g.defaultshow}
                        >
                            {useTextAreaSignInput == 1 ?
                                <WeaRichText.Textarea ecId={`${this && this.props && this.props.ecId || ''}_undefined@rg7vde@ec2`}
                                    viewAttr={"2"}
                                    value={phraseDescValue}
                                    onChange={this.onChange}
                                    onToolsChange={this.buttonBtnChange}
                                    bottomBarConfig={[]}
                                    extentsConfig={[]}
                                    onKeyDown={this.onKeyDown}
                                    ref={'WeaRichText_phrase'}
                                /> : <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@s8v5ex@ec3`}
                                    key="_wfphrase-edit"
                                    value={phraseDescValue}
                                    ckConfig={this.getCkConfig()}
                                    // id={"wfphraseEdit"} 
                                    extentsConfig={extentsConfig}
                                    onToolsChange={this.buttonBtnChange}
                                    onStatusChange={this.doStatusChange}
                                    ref={'WeaRichText_phrase'}
                                    layout={window}
                                />}
                        </WeaSearchGroup>
                    )
            });
        }

        return (
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@126ltd`}
                title={phraseEditDialogTitle}
                visible={visiable}
                key={visiable}
                icon='icon-coms-workflow'
                iconBgcolor='#0079DE'
                onCancel={() => {
                    onCancelEdit();//当前页面的store中的visiable置为false
                    setVisiable(false);//父级的visiable置为false
                }}
                buttons={this.getDialogBtns()}
                style={{ width: 800, height: 600 }}
                draggable={true}
                hasScroll
                layout={controlLayout}
                parentClassName="wf-add-common-sign-dialog"
            >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@rzsvfv`}
                    datas={this.getMoreBtns()}
                >
                    {conditionGroup}
                </WeaRightMenu>
                {/*收藏*/}
                <WeaCollect ecId={`${this && this.props && this.props.ecId || ''}_WeaCollect@m1vwaf`}
                    visible={showCollect}
                    favname=''
                    favouritetype={'5'}
                    importantlevel={1}
                    onClose={() => this.setState({ showCollect: false })}
                    submitBack={data => console.log('onOk: ', data)}
                />
            </WeaDialog> 
        );
    }

    doStatusChange = (status) => {
        if (status === "ready") {
            window.CK_REF.wfphraseEdit = this.refs.WeaRichText_phrase;
        }
    }

    onKeyDown = (e) => {
        e.stopPropagation();
    }

    buttonBtnChange = (name = '', ids = '', list = [], type = '', addfileid = '')  => {
        let returnInfo = [];
        if (name === 'Upload') {
            if (type === 'image') {
                list.map(item => {
                    const imglink = `/weaver/weaver.file.FileDownload?fileid=${item.fileidCode}`;
                    returnInfo.push(`<img src='${imglink}' data-imgsrc='${imglink}' alt=''/>&#8203;`);
                });
                return returnInfo.join(',');
            }
        }
        return ' ';
    }
    /**
     * 保存
     */
    doSave = () =>  {
        const { store } = this.props;
        const { isRequired, form, phraseDescValue, setStates } = store;
        let _phraseDescValue = phraseDescValue;
        if (window.CK_REF.wfphraseEdit) {
            _phraseDescValue = window.CK_REF.wfphraseEdit.getData();
            setStates({ phraseDescValue: _phraseDescValue })
        }
        if (!_phraseDescValue) {
            Modal.warning({ title: getLabel(131329, '信息确认'), okText: getLabel(33703, '确认'), content: getLabel(384146, '必要信息不完整，红色*为必填项') });
            return;
        }
        const { saveCallBack } = this.props;
        const formParams = form.getFormParams();
        const { groupid = '', dsporder = 0 } = formParams;
        if (groupid == '1' && dsporder < 0) {
            Modal.warning({ title: getLabel(131329, '信息确认'), okText: getLabel(33703, '确认'), content: getLabel(385772, '显示顺序不能为负数！') });
            return;
        }

        store.onSave(saveCallBack);//weaworkflow_userdefault_store.getConditionInfo
    }

    /**
     * 富文本编辑器输入onChange事件
     * @param desc
     */
    onChange = (desc = '') => {
        const { store } = this.props;
        const { richTextOnChange, setStates } = store;
        richTextOnChange(desc);
        setStates({
            isRequired: desc === '' ? 'required' : ''
        });
    }

    /**
     * 富文本编辑器配置参数
     * @returns {{height: number, toolbar: string, toolbar_Full: *[]}}
     */
    getCkConfig() {
        return {
            height: 240,
            removePlugins: 'resize',
            toolbar: [{ name: 'document', items: ['Source'] },
            { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike',] },
            { name: 'styles', items: ['Font', 'FontSize'] },
            { name: 'colors', items: ['TextColor', 'BGColor'] },
            {
                name: 'paragraph',
                items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']
            },
            { name: 'links', items: ['Link', 'Unlink'] },
            { name: 'tools', items: ['Maximize'] },
            { name: 'insert', items: ['Table', '-', 'Undo', 'Redo'] }],
            uploadUrl: '/api/doc/upload/uploadFile'
        };
    }

    getDialogBtns = () =>  {
        const { store } = this.props;
        return [
            (
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@eo59iw@save`}
                    type="primary"
                    disabled={store.saveDisable}
                    onClick={this.doSave}>{getLabel(30986, '保存')}
                </Button>),
            (<WeaMoreButton ecId={`${this && this.props && this.props.ecId || ''}_WeaMoreButton@5lrzfp@more`} datas={this.getMoreBtns()} />)
        ];
    }

    initExtentsConfig(extentsConfig) {
        extentsConfig.push({
            name: 'Upload',
            type: 'image',
            show: <div className="wea-cb-item">
                <span className={`wea-cbi-icon cke_button_icon cke_button__image_icon`} />
            </div>,
            uploadUrl: '/api/doc/upload/uploadFile',
            category: 'all',
            limitType: 'jpg,gif,png',
            title: getLabel(20001, '上传图片'),
            needLoading: false
        });
    }

    getMoreBtns() {
        return [{
            key: "save",
            icon: <i className='icon-workflow-Right-menu-Preservation' />,
            content: getLabel(30986, '保存'),
            onClick: () => {
                this.doSave();
            }
        }, {
            key: "coll",
            icon: <i className='icon-coms-Collection' />,
            content: getLabel(28111, '收藏'),
            onClick: () => {
                this.setState({
                    showCollect: true,
                });
            }
        }
        ];
    }

}


